package com.wechat.controller;

import com.wechat.apidoc.WxPayNoticeInterface;
import com.wechat.entity.User;
import com.wechat.service.PayService;
import com.wechat.service.UserService;
import com.wechat.service.UserWithdrawcashService;
import com.wechat.utils.ActionResult;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Map;


/**
 * 微信小程序支付接口
 *
 * @author cgc
 * @date 2018/4/11
 */
@RestController
@RequestMapping("/api/v1")
public class WxPayController implements WxPayNoticeInterface {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 提现最低金额 单位分
     */
    @Value("${wxpay.withdrawCash.minamount:30}")
    private int wxPayWithdrawCashMinAmount;

    @Autowired
    private PayService payService;
    @Autowired
    private UserWithdrawcashService userWithdrawcashService;
    @Autowired
    private UserService userService;

    /**
     * 发起支付
     */
    @Override
    @RequestMapping(value = "/pay/payment", method = RequestMethod.POST)
    public ActionResult unifiedOrder(String key, BigDecimal totalFee, HttpServletRequest request) {

        logger.info("[用户发起支付接口]:{}", "key=" + key);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        user = userService.findById(user.getId());
        try {

            Map<String, String> resultMap = payService.unifiedOrder(user, totalFee,null, request);

            result.setData(resultMap);
            result.setSuccess(true);
            result.setMessage("用户发起支付成功");

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("用户发起支付接口异常提现失败");

            logger.warn("[用户发起支付接口异常]：", e);
        }

        return result;
    }


    /**
     * 支付异步通知
     */
    @RequestMapping(value = "/pay/notify", method = RequestMethod.POST)
    public String notify(HttpServletRequest request, HttpServletResponse response) {



        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), "UTF-8"));

            String buffer = null;
            StringBuffer xml = new StringBuffer();
            while ((buffer = br.readLine()) != null) {
                xml.append(buffer);
            }

            logger.info("[支付异步通知接口]:{}", "notifyXml=" + xml);

            Boolean result = payService.notify(xml.toString());
            if(result){
                String xmlString = "<xml>\n" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                        "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                        "</xml>";
                return xmlString;
            }

        } catch (Exception e) {
            logger.warn("[支付异步通知接口异常]：", e);
        }

        return null;
    }

    /**
     * 发起提现
     */
    @Override
    @RequestMapping(value = "/pay/withdrawCash", method = RequestMethod.POST)
    public ActionResult withdrawCash(String key, BigDecimal amount) {

        logger.info("[用户提现接口]:{}", "key=" + key);

        ActionResult result = new ActionResult<>();

        User user = userService.getLoginUser(key);
        if (user == null) {
            result.setLoginTimeout(true);
            result.setMessage("用户登录超时");
            return result;
        }

        BigDecimal minAmount =  new BigDecimal((double)wxPayWithdrawCashMinAmount/(double)100);
        if(amount.compareTo(minAmount) < 0){
            result.setSuccess(false);
            result.setMessage("提现金额过低");
            return result;
        }

        user = userService.findById(user.getId());
        if(user.getBalance().compareTo(amount) < 0){
            result.setSuccess(false);
            result.setMessage("用户余额不足");
            return result;
        }

        try {
            if (userWithdrawcashService.withdrawCash(user, amount)) {
                result.setSuccess(true);
                result.setMessage("用户提现成功");
            } else {
                result.setSuccess(false);
                result.setMessage("用户提现失败");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("用户提现接口异常提现失败");

            logger.warn("[用户提现接口异常]：", e);
        }

        return result;
    }

}
